package cn.itcast.bos.service.system.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuRepository;
import cn.itcast.bos.dao.system.PermissionRepository;
import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService{
	
	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private PermissionRepository permissionRepository;
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Role> findByUser(User user) {
		if(user.getUsername().equals("admin")){
			return roleRepository.findAll();
		}else{
			//不为总管理员就返回所需的角色
			return roleRepository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	//保存角色对象
	@Override
	public void save(Role role, String[] permissionIds, String menuId) {
		if(role != null){
			if(permissionIds != null && permissionIds.length > 0){
				for(String permissionId :permissionIds){
					Permission permission = permissionRepository.findOne(Integer.parseInt(permissionId));
					if(permission != null){
						role.getPermissions().add(permission);
					}
				}
			}
			String[] menuIds = menuId.split(",");
			if(menuIds != null && menuIds.length > 0){
				for(String id : menuIds){
					Menu menu = menuRepository.findOne(Integer.parseInt(id));
					if(menu != null){
						role.getMenus().add(menu);
					}
				}
			}
			//保存role
			roleRepository.save(role);
		}
	}

}
